#!/bin/bash
# chkconfig: 2345 90 10
# description: UnblockNeteaseMusic: a tool to unlock NetEase cloud music.

### BEGIN INIT INFO
# Provides:          UnblockNeteaseMusic
# Required-Start:    $network $syslog
# Required-Stop:     $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: UnblockNeteaseMusic: a tool to unlock NetEase cloud music.
# Description:       Start or stop the UnblockNeteaseMusic
### END INIT INFO

NAME="UnblockNeteaseMusic"
NAME_BIN="UnblockNeteaseMusic"
FOLDER="/usr/local/UnblockNeteaseMusic"
FILE="${FOLDER}/app.js"
FILE_CONF="${FOLDER}/UnblockNeteaseMusic.conf"
FILE_LOG="${FOLDER}/UnblockNeteaseMusic.log"
FOLDER_NODE="/usr/local/UnblockNeteaseMusic/node"
FILE_NODE="/usr/local/UnblockNeteaseMusic/node/bin/node"

GREEN_FONT_PREFIX="\033[32m" && RED_FONT_PREFIX="\033[31m" && GREEN_BACKGROUND_PREFIX="\033[42;37m" && RED_BACKGROUND_PREFIX="\033[41;37m" && FONT_COLOR_SUFFIX="\033[0m"
INFO="${GREEN_FONT_PREFIX}[信息]${FONT_COLOR_SUFFIX}" && ERROR="${RED_FONT_PREFIX}[错误]${FONT_COLOR_SUFFIX}" && TIP="${GREEN_FONT_PREFIX}[注意]${FONT_COLOR_SUFFIX}"
RETVAL=0

_CHECK_PID(){
	PID=$(ps -ef |grep "${NAME_BIN}" |grep -v "grep" |grep -v "init.d" |grep -v "service" |awk '{print $2}')
	if [[ ! -z "${PID}" ]]; then
		return 0
	else
		return 1
	fi
}
_CONFIG_READ(){
	[[ ! -e ${FILE_CONF} ]] && echo -e "${ERROR} ${NAME} 配置文件不存在 !" && exit 1
	PORT=$(cat ${FILE_CONF}|grep 'PORT = '|awk -F 'PORT = ' '{print $NF}')
	SOURCE=$(cat ${FILE_CONF}|grep 'SOURCE = '|awk -F 'SOURCE = ' '{print $NF}')
	STRICT=$(cat ${FILE_CONF}|grep 'STRICT = '|awk -F 'STRICT = ' '{print $NF}')
}
_START(){
	_CHECK_PID
	if [[ ${?} == 0 ]]; then
		echo -e "${INFO} $NAME (PID ${PID}) 正在运行..." && exit 0
	else
		_CONFIG_READ
		echo -e "${INFO} $NAME 启动中..."
		ulimit -n 51200
		if [[ "${STRICT}" == "NO" ]]; then
			nohup "${FILE_NODE}" "${FILE}" -a 0.0.0.0 -p ${PORT} -o ${SOURCE} > "${FILE_LOG}" 2>&1 &
		else
			nohup "${FILE_NODE}" "${FILE}" -a 0.0.0.0 -p ${PORT} -o ${SOURCE} -s -e "http://music.163.com" > "${FILE_LOG}" 2>&1 &
		fi
		sleep 2s
		_CHECK_PID
		if [[ ${?} == 0 ]]; then
			echo -e "${INFO} $NAME 启动成功 !"
		else
			echo -e "${ERROR} $NAME 启动失败(请运行脚本查看日志错误输出内容) !"
		fi
	fi
}
_STOP(){
	_CHECK_PID
	if [[ ${?} == 0 ]]; then
		kill -9 "${PID}"
		RETVAL=${?}
		if [[ ${RETVAL} == 0 ]]; then
			echo -e "${INFO} $NAME 停止成功 !"
		else
			echo -e "${ERROR} $NAME 停止失败 !"
		fi
	else
		echo -e "${INFO} $NAME 未运行"
		RETVAL=1
	fi
}
_STATUS(){
	_CHECK_PID
	if [[ ${?} == 0 ]]; then
		_CONFIG_READ
		echo -e "${INFO} $NAME (PID ${PID}) 正在运行..."
	else
		echo -e "${INFO} $NAME 未运行 !"
		RETVAL=1
	fi
}
_RESTART(){
	_STOP
	_START
}
case "$1" in
	start|stop|restart|status)
	INDEX=$(echo ${1}|sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/')
	_${INDEX}
	;;
	*)
	echo -e "使用方法: $0 { start | stop | restart | status }"
	RETVAL=1
	;;
esac
exit $RETVAL